//
//  PreviewLayer.cpp
//  BayMaxPuzzle
//
//  Created by Jacky on 15/3/28.
//
//

#include "PreviewLayer.h"
#include "CocosAds.h"

USING_NS_CC;

bool PreviewLayer::isExist = false;

PreviewLayer* PreviewLayer::create(std::string photo, int decorationIndex)
{
    PreviewLayer *pRet = new(std::nothrow) PreviewLayer();
    if (pRet && pRet->init(photo, decorationIndex))
    {
        pRet->autorelease();
        return pRet;
    }
    else
    {
        delete pRet;
        pRet = NULL;
        return NULL;
    }
}

// on "init" you need to initialize your instance
bool PreviewLayer::init(std::string photo, int decorationIndex)
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() || isExist)
    {
        return false;
    }
    
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();
    
    isExist = true;
    
    ignoreAnchorPointForPosition(false);
    this->setPosition(Vec2(350, visibleSize.height/2 + origin.y));
    this->setScale(0.01);
    this->setOpacity(0);
    
    auto fadein = FadeIn::create(0.3);
    auto ease = EaseBackOut::create(ScaleTo::create(0.5, 1));
    this->runAction(Spawn::create(fadein, ease, nullptr));
    
    initTouchEventlistener();
    
    _photoName = photo;
    
    auto sprite = Sprite::create(photo);
    sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
    this->addChild(sprite);
    
    char buffer[20];
    sprintf(buffer, "decoration_%d.png", decorationIndex);
    auto decoration = Sprite::create(buffer);
    decoration->setPosition(sprite->getPosition());
    this->addChild(decoration);
    
    return true;
}

void PreviewLayer::initTouchEventlistener()
{

    auto listener = EventListenerTouchOneByOne::create();
    listener->onTouchBegan = [=](Touch *touch,Event *event){
        return false;
    };

    listener->setSwallowTouches(true);
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
}

void PreviewLayer::destroy()
{
    CocosAds::getInstance()->showInterstitial("886979552o4gyjn");
    CocosAds::getInstance()->setInterstitialCloseMode(0);
    auto ease = EaseBackIn::create(ScaleTo::create(0.5, 0.01));
    auto callfunc = CallFunc::create([=](){
        isExist = false;
        this->removeFromParent();
    });
    this->runAction(Sequence::create(ease, callfunc, nullptr));

}